// Copyright 2012 Google Inc. All Rights Reserved.
//
// Licensed under the Apache License, Version 2.0 (the "License");
// you may not use this file except in compliance with the License.
// You may obtain a copy of the License at
//
//     http://www.apache.org/licenses/LICENSE-2.0
//
// Unless required by applicable law or agreed to in writing, software
// distributed under the License is distributed on an "AS IS" BASIS,
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
// See the License for the specific language governing permissions and
// limitations under the License.

#include "worker.h"

#include <string>
#include "glog/logging.h"

#include "connection.h"

namespace seven_summits {

void* call_loop(void* w) {
  Worker* worker = reinterpret_cast<Worker*>(w);
  return worker->ProcessingLoop();
}

bool Worker::Init() {
  VLOG(2) << "Worker::Init()\n";
  return !pthread_create(&this->thread_, NULL, &call_loop, this);
}

void Worker::ProcessAsync(const SmtRequest& request, SmtResponse* response,
                          Connection* connection) {
  if (request.format() != SmtRequest::COMPLETE
      || request.compression() != SmtRequest::NONE) {
    response->set_status(SmtResponse::NOT_IMPLEMENTED);
    connection->WriteResponse();
    return;
  }
  WorkItem work;
  work.request = &request;
  work.response = response;
  work.connection = connection;
  pthread_mutex_lock(&cond_mutex_);
  pthread_mutex_lock(&work_items_mutex_);
  work_items_.push_back(work);
  pthread_mutex_unlock(&work_items_mutex_);
  pthread_cond_signal(&cond_);
  pthread_mutex_unlock(&cond_mutex_);
}

bool Worker::HasEmptyWorkQueue() {
  pthread_mutex_lock(&work_items_mutex_);
  bool is_empty = work_items_.empty();
  pthread_mutex_unlock(&work_items_mutex_);
  return is_empty;
}

void* Worker::ProcessingLoop() {
  while (true) {
    while (HasEmptyWorkQueue()) {
      pthread_mutex_lock(&cond_mutex_);
      pthread_cond_wait(&cond_, &cond_mutex_);
      pthread_mutex_unlock(&cond_mutex_);
    }
    Solve();
    connection()->WriteResponse();
    pthread_mutex_lock(&work_items_mutex_);
    work_items_.pop_front();
    pthread_mutex_unlock(&work_items_mutex_);
  }
  pthread_exit(NULL);
}

pthread_once_t WorkerFactory::module_init_ = PTHREAD_ONCE_INIT;
std::map<std::string, WorkerFactory*>* WorkerFactory::factory_map_;

void WorkerFactory::InitRegistry() {
  factory_map_ = new std::map<std::string, WorkerFactory*>();
}

void WorkerFactory::Register(const std::string& name, WorkerFactory* factory) {
  pthread_once(&module_init_, InitRegistry);
  (*factory_map_)[name] = factory;
}

WorkerFactory* WorkerFactory::GetByName(const std::string& name) {
  pthread_once(&module_init_, InitRegistry);
  std::map<std::string, WorkerFactory*>::const_iterator item =
      factory_map_->find(name);
  CHECK(item != factory_map_->end()) << "could not find " << name;
  return item->second;
}

}  // namespace seven_summits
